<template>
  <div class="content">
    <el-card class="box-card card_left" :style="{ width: width }">
      <span> <i class="el-icon-help mRight6"></i>测点资源树 </span>

      <div class="searchInput">
        <el-select
          @change="selectBridge"
          size="small"
          width="100%"
          v-model="bridgeId"
          filterable
          placeholder="请选择桥梁"
        >
          <el-option
            v-for="item in bridgeAllList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>

      <el-tree
        ref="tree"
        node-key="id"
        show-checkbox
        @check="handleCheckChange"
        :check-on-click-node="true"
        :check-strictly="true"
        :default-checked-keys="checkedKeys"
        style="margin-top: 10px"
        :data="[getPointTreeList]"
        :props="defaultProps"
        default-expand-all
        @node-click="handleNodeClick"
      ></el-tree>
    </el-card>

    <el-card
      v-if="width == '13%'"
      class="box-card card_left"
      :style="{ width: width }"
    >
      <span> <i class="el-icon-help mRight6"></i>构件列表 </span>

      <el-tree
        style="margin-top: 10px"
        :data="getPointNextTreeList"
        :props="defaultProps"
        default-expand-all
        @node-click="handleListClick"
      ></el-tree>
    </el-card>

    <el-card class="box-card card_right" :style="{ width: rightWidth }">
      <div v-if="displaynone" style="overflow: hidden">
        <el-row :gutter="10">
          <!-- <el-col :span="6">
            <el-input v-show="false" v-model="name" placeholder="请输入..." size="small"></el-input>
          </el-col>
          <el-col :span="6">
            <el-button v-show="false" type="primary" size="small">查询</el-button>
          </el-col>-->
          <el-col style="text-align: right" :span="24">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="addEquipment"
              >新增测点</el-button
            >
          </el-col>
        </el-row>
        <!-- 表格 -->
        <el-table
          :data="
            getPointListState.currentPageData
              ? getPointListState.currentPageData
              : []
          "
          :header-cell-style="{
            background: '#8595B9',
            color: '#fff',
            height: '44px',
          }"
          size="small"
          stripe
        >
          <el-table-column prop="name" label="测点名称"></el-table-column>
          <el-table-column prop="code" label="测点编号"></el-table-column>
          <el-table-column
            prop="crossSectionName"
            label="所属截面名称"
          ></el-table-column>
          <el-table-column prop="createTime" label="创建时间">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime | YMDHMS }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template slot-scope="scope">
              <el-tooltip content="详情">
                <el-button
                  type="text"
                  icon="el-icon-warning-outline"
                  @click="particulars(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="修改">
                <el-button
                  type="text"
                  icon="el-icon-edit-outline"
                  @click="handleEdit(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除">
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  style="color: red !important"
                  @click="handleDelete(scope.$index, scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            @current-change="handleCurrentChange"
            v-if="getPointListState.total_sum"
            :page-size="15"
            background
            layout="prev, pager, next"
            :total="getPointListState.total_sum"
            :current-page="pageNum"
          ></el-pagination>
        </div>
      </div>
      <!-- 基础信息组件 -->
      <div v-else class="box_two">
        <el-row
          :gutter="10"
          style="border-bottom: 1px solid #e8e8e8; height: 40px"
        >
          <el-col :span="12">
            <span class="titletop">{{ detailTile }}</span>
          </el-col>
          <el-col :span="12">
            <el-button
              type="primary"
              icon="el-icon-arrow-left"
              size="small"
              @click="gotback"
              >返回</el-button
            >
          </el-col>
        </el-row>
        <!-- 组件切换-->
        <div class="tab-wrapper">
          <el-tabs>
            <el-tab-pane label="基础信息">
              <basicInformation
                :selectRow="selectRow"
                :deviceData="deviceData"
              ></basicInformation>
            </el-tab-pane>
            <el-tab-pane label="测值项">
              <measurementValue :selectRow="selectRow"></measurementValue>
            </el-tab-pane>
            <el-tab-pane label="报警配置">
              <policeConfig :selectRow="selectRow"></policeConfig>
            </el-tab-pane>
            <!-- <el-tab-pane label="计算公式">
              <computational></computational>
            </el-tab-pane> -->
            <!-- <el-tab-pane label="所属分类">
              <whatClassify></whatClassify>
            </el-tab-pane>-->
            <el-tab-pane label="关联测点">
              <relevanceStation :selectRow="selectRow"></relevanceStation>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-card>
    <!-- 新增弹框 -->
    <vx-popup
      :title="addtitle"
      width="500px"
      @close="closeFormSubmitData"
      :active.sync="cardDialogVisible"
      @confirmPopup="submit"
      @cancelPopup="cancelFormSubmitData"
    >
      <el-form
        :model="addRuleForm"
        :rules="addRules"
        ref="addRefRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="测点名称：" prop="name">
          <el-input
            v-model="addRuleForm.name"
            placeholder="请输入测点名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="测点编号：" prop="code">
          <el-input
            v-model="addRuleForm.code"
            placeholder="请输入测点编号"
          ></el-input>
        </el-form-item>
        <el-form-item label="测点单位：" prop="pointUnit">
          <el-input
            v-model="addRuleForm.pointUnit"
            placeholder="请输入测点单位"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属截面：" prop="crossSectionId">
          <el-select
            v-model="addRuleForm.crossSectionId"
            placeholder="请选择所属截面"
          >
            <el-option
              v-for="item in getBridgeCrossSections"
              :key="item.id"
              :label="item.sectionName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属设备：" prop="deviceId">
          <el-select
            v-model="addRuleForm.deviceId"
            placeholder="请选择所属设备"
          >
            <el-option
              v-for="item in deviceList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="一级分类：" prop="measurePointFirstTypeId">
          <el-select
            v-model="addRuleForm.measurePointFirstTypeId"
            @change="selectChange"
            placeholder="请选择一级分类"
          >
            <el-option
              v-for="item in firstType"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="二级分类：" prop="measurePointSecondTypeId">
          <el-select
            v-model="addRuleForm.measurePointSecondTypeId"
            placeholder="请选择二级分类"
          >
            <el-option
              v-for="item in secondType"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </vx-popup>
  </div>
</template>

<script>
import basicInformation from "./components/basicInformation"; //基础信息
import measurementValue from "./components/measurementValue"; //测值项
import policeConfig from "./components/policeConfig"; //报警配置
import computational from "./components/computational"; //计算公式
import whatClassify from "./components/whatClassify"; //所属分类
import relevanceStation from "./components/relevanceStation"; //关联测点
import { deepClone } from "@/util.js";

import { mapState, mapActions, mapMutations } from "vuex";

export default {
  data() {
    return {
      total: "5",
      width: "18%", // 13  18
      rightWidth: "81%", // 72 81
      displaynone: true,
      detailTile: "",
      deviceList: [],
      getBridgeCrossSections: [],
      selectRow: "",
      deviceData: "",
      showBtn: false,
      main: false,
      // bridgeAllList: [],
      bridgeId: "",
      name: "",
      cardDialogVisible: false,
      addtitle: "新增测点",
      defaultProps: {
        children: "children",
        label: "name",
      },
      // 当前页码
      pageNum: 1,

      //   表单数据
      addRuleForm: {
        name: "",
        place: "",
        pointUnit:'',
        crossSectionId: "",
        deviceId: "",
        measurePointSecondTypeId: "",
        measurePointFirstTypeId: "",
      },
      //   验证规则
      addRules: {
        name: [{ required: true, message: "请输入测点名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入测点编号", trigger: "blur" }],
        crossSectionId: [
          { required: true, message: "请选择截面", trigger: "blur" },
        ],
        deviceId: [{ required: true, message: "请选择设备", trigger: "blur" }],
        measurePointSecondTypeId: [
          { required: true, message: "请选择一级分类", trigger: "blur" },
        ],
        measurePointFirstTypeId: [
          { required: true, message: "请选择二级分类", trigger: "blur" },
        ],
      },
      checkedKeys: [],
    };
  },
  components: {
    basicInformation,
    measurementValue,
    policeConfig,
    computational,
    whatClassify,
    relevanceStation,
  },
  computed: {
    ...mapState("mpsModule", {
      initBridgeId: "InitBridgeId",
      bridgeAllList: "bridgeAllList",
      getPointTreeList: "getPointTree",
      getPointNextTreeList: "getPointNextTree",
      getPointListState: "getPointList",
      structureId: "structureId", // 部件id
      componentId: "componentId", // 构件id
      firstType: "firstType",
      secondType: "secondType",
    }),
    // 获取设备名称
    deviceId() {
      return (id) => {
        let data = this.deviceList.filter((item) => item.id == id);
        return data[0];
      };
    },
    // 获取截面名称
    crossSectionName() {
      return (id) => {
        let data = this.getBridgeCrossSections.filter((item) => item.id == id);
        return data[0] ? data[0].sectionName : "";
      };
    },
  },

  created() {},
  mounted() {
    this.getBridgeAllList();
    // 获取一级分类   getSecondType getFirstType
    this.getFirstType();

    // 获取二级分类
  },
  methods: {
    ...mapActions("mpsModule", {
      getBridgeAllList: "getBridgeAllList",
      getPointTree: "getPointTree",
      getPointNextTree: "getPointNextTree",
      getPointListAction: "getPointList",
      getBridgePointList: "getBridgePointList",
      getFirstType: "getFirstType",
      getSecondType: "getSecondType",
    }),
    ...mapMutations("mpsModule", {
      setInitBridgeId: "INITBRIDGEID",
      structureIdMutations: "STRUCTUREID",
      componentIdMutations: "COMPONENTID",
      getPointNextree: "GETPOINTNEXTTREE",
    }),
    selectBridge(e) {
      this.setInitBridgeId(e);
      // console.log("当前桥梁的id", this.initBridgeId);
      this.getPointTree({
        bridgeId: e,
        pId: "-1",
      });
    },
    selectChange(e) {
      // console.log(e);
      this.$set(this.addRuleForm, "measurePointSecondTypeId", "");
      // 获取二级分类
      this.getSecondType({
        parentId: e,
      });
    },

    //   树节点被点击时的回调
    handleNodeClick(data, Node, s) {
      this.checkedKeys = [data.id];
      this.$refs["tree"].setCheckedKeys([data.id]);
      this.showBtn = false;
      if (Node.level == 1) {
        this.main = true;
        // 获取全部列表
        this.pageNum = 1;
        this.getBridgePointList({
          ownId: this.initBridgeId,
          pageSize: 15,
          pageNum: this.pageNum,
        });
      } else {
        this.main = false;
      }
      this.structureIdMutations(data.id);
      // 获取第二颗树
      this.getPointNextTree({
        ownId: this.bridgeId,
        structureId: data.id,
      });
    },
    handleCheckChange(data) {
      this.checkedKeys = [data.id];
      this.$refs["tree"].setCheckedKeys([data.id]);

      this.showBtn = false;
      if (data.type == "own") {
        this.main = true;
        // 获取全部列表
        this.pageNum = 1;
        this.getBridgePointList({
          ownId: this.initBridgeId,
          pageSize: 15,
          pageNum: this.pageNum,
        });
      } else {
        this.main = false;
      }
      this.structureIdMutations(data.id);
      // 获取第二颗树
      this.getPointNextTree({
        ownId: this.bridgeId,
        structureId: data.id,
      });
    },
    // 点击构件列表
    handleListClick(data, Node, s) {
      // console.log("点击的构件列表", data);
      this.showBtn = true;
      this.componentIdMutations(data.id);
      //  查询测点列表
      this.pageNum = 1;
      this.getPointListAction({
        ownId: this.initBridgeId,
        componentId: data.id,
        pageSize: 15,
        pageNum: this.pageNum,
      });
    },
    // 分页事件
    handleCurrentChange(e) {
      // console.log("当前页码", e);
      this.pageNum = e;
      //  查询测点列表
      if (this.getPointNextTreeList.length > 0) {
        this.getPointListAction({
          ownId: this.initBridgeId,
          componentId: this.componentId,
          pageSize: 15,
          pageNum: this.pageNum,
        });
      } else {
        this.getBridgePointList({
          ownId: this.initBridgeId,
          pageSize: 15,
          pageNum: this.pageNum,
        });
      }
    },
    // 关闭弹框
    closeFormSubmitData() {
      this.cardDialogVisible = false;
      this.$refs.addRefRuleForm.resetFields();
    },
    // 取消弹框
    cancelFormSubmitData() {
      this.cardDialogVisible = false;
      this.$refs.addRefRuleForm.resetFields();
    },
    // 提交弹框
    submit() {
      if (this.addtitle == "修改测点") {
        this.cardDialogVisible = false;
        this.$refs.addRefRuleForm.validate((valid) => {
          // 修改
          if (!valid) return;
          // console.log("修改数据++++++", this.addRuleForm);
          //触发更新接口
          this.addRuleForm.crossSectionName = this.crossSectionName(
            this.addRuleForm.crossSectionId
          );
          delete this.addRuleForm._id;
          delete this.addRuleForm.createTime;
          delete this.addRuleForm.updateTime;
          // 增加 x y
          if (!this.addRuleForm.xaxis) {
            this.addRuleForm.xaxis = 0;
          }
          if (!this.addRuleForm.yaxis) {
            this.addRuleForm.yaxis = 0;
          }

          this.$api.mearsuringPointSetting
            .uupdatePoint({
              ...this.addRuleForm,
            })
            .then((res) => {
              if (res.data.success) {
                this.$vs.notify({
                  text: "修改成功",
                  color: "success",
                  icon: "success",
                });
                this.getPointListAction({
                  ownId: this.initBridgeId,
                  componentId: this.componentId,
                  pageSize: 15,
                  pageNum: this.pageNum,
                });
              }
            });
        });
      } else {
        // 新增
        this.$refs.addRefRuleForm.validate((valid) => {
          if (!valid) return;
          this.cardDialogVisible = false;
          this.addRuleForm.crossSectionName = this.crossSectionName(
            this.addRuleForm.crossSectionId
          );
          // console.log(this.addRuleForm);
          // 触发新增接口
          this.$api.mearsuringPointSetting
            .addPoint({
              ownId: this.initBridgeId,
              componentId: this.componentId,
              ...this.addRuleForm,
            })
            .then((res) => {
              // console.log("新增成功", res);
              if (res.data.success) {
                this.$vs.notify({
                  text: "新增成功",
                  color: "success",
                  icon: "success",
                });
                // 重新获取列表
                //  查询测点列表
                this.getPointListAction({
                  ownId: this.initBridgeId,
                  componentId: this.componentId,
                  pageSize: 15,
                  pageNum: this.pageNum,
                });
              }
            });
        });
      }
    },
    // 表格详情跳转
    particulars(row) {
      this.detailTile = row.name;
      this.displaynone = false;
      // 保存当前选中的行数据
      this.selectRow = row;
      // 根据设备 id 查设备详细信息
      let data = this.deviceId(this.selectRow.deviceId);
      this.deviceData = data;
    },
    // 表格行编辑
    handleEdit(row) {
      // console.log(row);
      this.cardDialogVisible = true;
      this.addtitle = "修改测点";
      this.addRuleForm = deepClone(row);
    },
    // 新增弹框
    addEquipment() {
      if (this.main) {
        this.$vs.notify({
          text: "请选择部件",
          color: "warning",
          icon: "warning",
        });
        return false;
      }
      if (this.getPointNextTreeList.length == 0) {
        this.$vs.notify({
          text: "请新增构件",
          color: "warning",
          icon: "warning",
        });
        return false;
      }
      if (!this.showBtn) {
        this.$vs.notify({
          text: "请选择构件",
          color: "warning",
          icon: "warning",
        });
        return false;
      }

      this.cardDialogVisible = true;
      this.addtitle = "新增测点";
      this.addRuleForm = {};
    },
    // 表格行删除
    handleDelete(index, row) {
      // console.log(index, row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // console.log("删除成功", row);
          // 触发删除接口
          this.$api.mearsuringPointSetting
            .deletePoint({
              id: row.id,
            })
            .then((res) => {
              if (res.data.success) {
                this.$vs.notify({
                  text: "删除成功",
                  color: "success",
                  icon: "success",
                });
                // 重新获取列表数据
                if (this.getPointNextTreeList.length > 0) {
                  this.getPointListAction({
                    ownId: this.initBridgeId,
                    componentId: this.componentId,
                    pageSize: 15,
                    pageNum: this.pageNum,
                  });
                } else {
                  this.getBridgePointList({
                    ownId: this.initBridgeId,
                    pageSize: 15,
                    pageNum: this.pageNum,
                  });
                }
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 返回
    gotback() {
      this.displaynone = true;
    },

    // 查询桥梁下的所有 截面

    // 查询桥梁下的所有设备
    getDevice() {
      this.$api.mearsuringPointSetting
        .getDevice({
          ownId: this.initBridgeId,
        })
        .then((res) => {
          // console.log("获取桥梁下的设备", res);
          this.deviceList = res.data.data[0];
        });
    },
    // 查询桥梁下所有截面
    getBridgeCrossSectionsList() {
      this.$api.mearsuringPointSetting
        .getBridgeCrossSections({
          ownId: this.initBridgeId,
        })
        .then((res) => {
          // console.log("所有截面", res);
          this.getBridgeCrossSections = res.data.data[0];
        });
    },
  },

  watch: {
    bridgeAllList: function (newValue) {
      // console.log("newVal", newValue);
      if (newValue.length > 0) {
        this.setInitBridgeId(newValue[0].id);
        // this.checkedKeys = [newValue[0].id];
        // console.log("当前桥梁的id", this.initBridgeId);
        this.bridgeId = this.initBridgeId;
        this.getPointTree({
          bridgeId: newValue[0].id,
          pId: "-1",
        });
      }
    },
    getPointNextTreeList: function (newVal) {
      if (newVal.length > 0) {
        this.width = "13%";
        this.rightWidth = "72%";
      } else {
        // this.$vs.notify({
        //           text: "暂无构件信息",
        //           color: "warning",
        //           icon: "warning",
        //         });
        this.width = "18%";
        this.rightWidth = "81%";
      }
    },
    initBridgeId: function (newVal) {
      this.getPointNextree([]);
      this.checkedKeys = [this.initBridgeId];
      // 获取桥梁下的所有测点数据
      this.pageNum = 1;
      this.main = true;
      this.getBridgePointList({
        ownId: this.initBridgeId,
        pageSize: 15,
        pageNum: this.pageNum,
      });
      // 获取设备
      this.getDevice();
      // 获取截面
      this.getBridgeCrossSectionsList();
    },
    "addRuleForm.measurePointFirstTypeId": {
      handler(newVal) {
        if (newVal) {
          this.getSecondType({
            parentId: newVal,
          });
        }
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.card_left {
  span {
    .mRight6 {
      margin-right: 6px;
    }
    display: block;
    font-size: 16px;
    font-weight: 500;
    color: #327bdc;
    line-height: 30px;
    margin-bottom: 18px;
  }
}

.card_right {
  position: relative;
  .el-row {
    margin-bottom: 20px;
    .el-col-12:nth-child(2) {
      text-align: right;
    }
    .el-col-12:nth-child(3) {
      text-align: right;
    }
  }
  .page {
    // margin-top: 20px;
    width: 100%;
    text-align: center;
    position: absolute;
    bottom: 20px;
  }
  .box_two {
    .titletop {
      font-size: 16px;
      color: #327bdc;
      font-weight: 500;
      display: block;
      height: 32px;
      line-height: 32px;
    }
    .tab-wrapper {
      /deep/.el-tabs--top .el-tabs__item.is-top:nth-child(2) {
        padding-left: 20px;
      }
      /deep/.el-tabs--top .el-tabs__item.is-top:nth-child(5) {
        padding-right: 20px;
      }
      /deep/.el-tabs__nav-wrap::after {
        // background-color: none;
        z-index: -1;
      }
      /deep/.el-tabs__item.is-active {
        color: #fff;
        background: rgba(var(--vs-primary), 1) !important;
      }
      /deep/.el-tabs__item {
        height: 30px;
        line-height: 30px;
        margin-right: 20px;
        border-radius: 20px;
        background: #f2f2f2;
      }
      /deep/.el-tabs__item.is-active {
        color: #fff;
      }
      /deep/.el-tabs__active-bar {
        background: none;
      }
    }
  }
}
.searchInput {
  width: 100%;
}
/deep/.el-select {
  width: 100% !important;
}

// /deep/.el-tree--highlight-current
//   .el-tree-node.is-current
//   > .el-tree-node__content {
//   background-color: red !important;
//   height: 36px !important;
// }
</style>

